Page({
    data: {
      chatUser: {
        name: "未命名",
        avatar: "",
        id: "",
        status: "在线"
      },
      messageList: [],
      inputContent: "",
      scrollTop: 0
    },
  
    onLoad(options) {
      // 1. 接收并解码用户信息
      if (options.userInfo) {
        const userInfo = JSON.parse(decodeURIComponent(options.userInfo));
        this.setData({ chatUser: userInfo });
      }
      // 2. 加载模拟消息（根据 userId 区分不同聊天对象）
      this.loadMockMessages();
    },
  
    loadMockMessages() {
      const { id } = this.data.chatUser;
      let mockMessages = [];
      if (id === "1001") {
        // “一只小可爱”的初始消息
        mockMessages = [
          { msgId: "1", sender: "other", content: "图书馆三楼丢的电脑是我的～", time: "10:05" }
        ];
      } else if (id === "1002") {
        // “程心动”的初始消息
        mockMessages = [
          { msgId: "4", sender: "other", content: "核验成功！可以来六号楼拿走啦～", time: "09:30" }
        ];
      }
      this.setData({ messageList: mockMessages });
    },
  
    // 输入框内容变化时触发
  onInputChange(e) {
    const value = e.detail.value;
    // 实时打印输入内容（在控制台查看是否更新）
    console.log("输入内容：", value);
    this.setData({ inputContent: value });
  },

  // 发送消息函数
  sendMessage() {
    // 打印发送事件是否触发
    console.log("发送按钮被点击");
    const content = this.data.inputContent.trim();
    if (!content) return;
  
      // 构造自己的消息
      const newSelfMsg = {
        msgId: `self${Date.now()}`,
        sender: "self",
        content: content,
        time: this.formatTime(new Date())
      };
  
      // 更新消息列表 + 清空输入框
      this.setData({
        messageList: [...this.data.messageList, newSelfMsg],
        inputContent: ""
      });
  
      // 滚动到底部
      this.scrollToBottom();
  
      // 模拟对方回复（根据 userId 区分回复内容）
      setTimeout(() => {
        const reply = this.getMockReply(content);
        this.setData({ messageList: [...this.data.messageList, reply] });
        this.scrollToBottom();
      }, 1500);
    },
  
    scrollToBottom() {
      setTimeout(() => {
        const query = wx.createSelectorQuery().in(this);
        query.select(".chat-message-list").boundingClientRect(rect => {
          if (rect) this.setData({ scrollTop: rect.scrollHeight });
        }).exec();
      }, 100);
    },
  
    formatTime(date) {
      return `${date.getHours()}:${date.getMinutes()}`;
    },
  
    getMockReply(content) {
      const { id } = this.data.chatUser;
      if (id === "1001") {
        return content.includes("电脑") 
          ? "是一台银色 MacBook Pro，背面有贴纸～" 
          : "好的，等你消息～";
      } else if (id === "1002") {
        return content.includes("几点") 
          ? "下午 3 点到 5 点都可以～" 
          : "不客气～";
      }
      return "好的～";
    },
  
    goBack() {
      wx.navigateBack({ delta: 1 });
    }
  });  